1928D - Lonely Mountain Dungeons - CodeForces Solution


binary search brute force combinatorics data structures greedy math ternary search

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define pii pair<int, int>
#define endl '\n'
#define int ll

using namespace std;

vector<int> grp;
int N, b, X;

int f(int groups) {
    if(groups == 1) return 0;
    int ans = 0;
    for(int i = 0; i < N; i++) {
        if(grp[i] == 1) continue;
        int A = grp[i] / groups + ((grp[i] % groups) > 0);
        int B = grp[i] / groups;
        int A_cnt = grp[i] % groups;
        if(A_cnt == 0) A_cnt = groups;
        int B_cnt = min(grp[i], groups) - A_cnt;

        ans += (((A_cnt - 1)*(A_cnt)*A*A)/2LL)*b;
        ans += A_cnt*B_cnt*A*B*b;
        ans += (((B_cnt - 1)*(B_cnt)*B*B)/2LL)*b;
    }

    return ans - (groups - 1)*X;
}

int ternary_search(int l, int r) {
    int prev_l = -1, prev_r = -1;
    while (l <= r) {
        if(prev_l == l && prev_r == r) {
            int mx = f(l);
            for(int i = l + 1; i <= r; i++) {
                mx = max(mx, f(i));
            }

            return mx;
        }


        prev_l = l;
        prev_r = r;
        int m1 = l + (r - l) / 3;
        int m2 = r - (r - l) / 3;
        int f1 = f(m1);
        int f2 = f(m2);
        if (f1 < f2)
            l = m1;
        else
            r = m2;
    }
    return f(l);
}

void solve() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> N >> b >> X;
    grp.resize(N);

    int mx = 0;
    for(int i = 0; i < N; i++) {
        cin >> grp[i];
        mx = max(mx, grp[i]);
    }

    cout << ternary_search(1, mx) << endl;
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;

    while(t--)
        solve();
}


Comments

Submit
0 Comments
More Questions

780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem
1486B - Eastern Exhibition
1363A - Odd Selection
131B - Opposites Attract
490C - Hacking Cypher
158B - Taxi
41C - Email address
1373D - Maximum Sum on Even Positions
1574C - Slay the Dragon
621A - Wet Shark and Odd and Even
1395A - Boboniu Likes to Color Balls
1637C - Andrew and Stones
1334B - Middle Class
260C - Balls and Boxes
1554A - Cherry
11B - Jumping Jack